<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>客户端</title>
    <script type="text/javascript" src="webjars/jquery/3.4.1/jquery.js"></script>
</head>
<body>
    <div>
        用户名：
        <input type="text" class="username" />
        <input type="button" class="btn-connect" value="连接" />
    </div>
    <div>
        发送消息：
        <input type="text" class="msg" />
        <input type="button" class="btn-msg" value="发送" />
    </div>
</body>
<script type="text/javascript">
    var ws = null;

    //连接
    $('.btn-connect').click(function() {
        var username = $('.username').val();
        if (!username) {
            alert("用户名不能为空")
            return
        }
        connect(username);
    })

    //发送消息
    $('.btn-msg').click(function () {
        var msg = $('.msg').val()
        if (!msg) {
            alert("消息不能为空")
            return
        }
        sendMsg(msg);
    })

    function connect(username) {
        if (!window.WebSocket) {
            alert("您的浏览器不支持WebSocket")
        } else {
            var url = "ws://127.0.0.1:8081/webSocket/" + username
            ws = new WebSocket(url)

            ws.onopen = function () {
                console.log("打开连接")
            }

            ws.onclose = function () {
                ws = null
                console.log("关闭")
            }

            ws.onmessage = function (e) {
                console.log("接收消息:", e)
            }

            ws.onerror = function (e) {
                ws = null
                console.log("发送错误：", e)
            }
        }
    }

    function sendMsg(msg) {
        if (!ws) {
            alert("请先连接")
            return
        }

        ws.send(msg)
    }

</script>
</html>